/**
 * 浏览器工作流 - 弹出窗口脚本
 * 处理录制、回放、导入导出等核心功能
 */

document.addEventListener("DOMContentLoaded", function () {
  // 获取DOM元素
  const recordBtnEl = document.getElementById("record-btn");
  const recordStatusEl = document.getElementById("record-status");
  const playbackBtnEl = document.getElementById("playback-btn");
  const importFileEl = document.getElementById("import-file");
  const exportBtnEl = document.getElementById("export-btn");
  const cancelBtnEl = document.getElementById("cancel-btn");
  const exportSectionEl = document.getElementById("export-section");
  const actionsCountEl = document.getElementById("actions-count");
  const optionsBtnEl = document.getElementById("options-btn");
  const statusTextEl = document.getElementById("status-text");
  const timingModeEl = document.getElementById("timing-mode");
  const playbackSpeedEl = document.getElementById("playback-speed");

  // 状态变量
  let isRecording = false;
  let recordedActions = [];

  /**
   * 更新状态文本
   * @param {string} message - 状态消息
   * @param {string} type - 状态类型 (success, error, warning, info)
   */
  function updateStatus(message, type = "info") {
    statusTextEl.textContent = message;

    // 重置状态类
    statusTextEl.parentElement.className = "status";

    // 添加新的状态类
    if (type !== "info") {
      statusTextEl.parentElement.classList.add("status-" + type);
    }

    console.log(`[${type.toUpperCase()}] ${message}`);
  }

  /**
   * 更新录制状态UI
   * @param {boolean} recording - 是否正在录制
   * @param {number} actionCount - 已录制的操作数量
   */
  function updateRecordingUI(recording, actionCount = 0) {
    const recordIcon = recordBtnEl.querySelector(".record-icon");
    const recordText = recordBtnEl.querySelector(".record-text");
    const statusDot = recordStatusEl.querySelector(".status-dot");
    const statusText = recordStatusEl.querySelector(".status-text");

    isRecording = recording;

    if (recording) {
      recordBtnEl.classList.add("recording");
      recordIcon.textContent = "⏹";
      recordText.textContent = "停止录制";
      statusDot.classList.add("recording");
      statusText.textContent = actionCount > 0 ? `正在录制... (${actionCount} 个操作)` : "正在录制...";
      exportSectionEl.style.display = "none";
      playbackBtnEl.disabled = true;
    } else {
      recordBtnEl.classList.remove("recording");
      recordIcon.textContent = "⏺";
      recordText.textContent = "开始录制";
      statusDot.classList.remove("recording");
      statusText.textContent = actionCount > 0 ? `已录制 ${actionCount} 个操作` : "未录制";
      playbackBtnEl.disabled = false;

      if (actionCount > 0) {
        exportSectionEl.style.display = "block";
        actionsCountEl.textContent = actionCount;
      } else {
        exportSectionEl.style.display = "none";
      }
    }
  }

  /**
   * 检查当前标签页是否可用
   */
  async function checkCurrentTab() {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab) {
      throw new Error("没有找到当前标签页");
    }
    if (!tab.url || tab.url.startsWith("chrome://") || tab.url.startsWith("chrome-extension://") || tab.url.startsWith("edge://")) {
      throw new Error("当前页面不支持录制功能\n请在普通网页中使用此功能");
    }
    return tab;
  }

  /**
   * 确保content script已加载
   */
  async function ensureContentScript(tabId) {
    try {
      // 尝试发送测试消息
      const response = await chrome.tabs.sendMessage(tabId, { type: "PING" });
      if (response?.success) {
        console.log("Content script已加载");
        return true;
      }
    } catch (error) {
      console.log("Content script未加载，正在注入...");
    }

    // 注入content script
    await chrome.scripting.executeScript({
      target: { tabId: tabId },
      files: ["content/content.js"],
    });

    // 等待script加载完成
    await new Promise((resolve) => setTimeout(resolve, 800));

    // 验证注入结果
    const response = await chrome.tabs.sendMessage(tabId, { type: "PING" });
    if (!response?.success) {
      throw new Error("无法加载录制功能，请刷新页面后重试");
    }

    console.log("Content script注入并加载成功");
    return true;
  }

  /**
   * 开始录制
   */
  async function startRecording() {
    try {
      // 延迟500ms后关闭窗口
      setTimeout(() => {
        window.close();
      }, 500);

      updateStatus("正在启动录制...", "info");
      recordBtnEl.disabled = true;

      const tab = await checkCurrentTab();
      await ensureContentScript(tab.id);

      // 清空之前的录制
      recordedActions = [];

      // 向content script发送开始录制的消息
      const response = await chrome.tabs.sendMessage(tab.id, { type: "START_RECORDING" });

      if (!response?.success) {
        throw new Error(response?.error || "Content script响应失败");
      }

      updateRecordingUI(true, 0);
      updateStatus("录制已开始，请在页面中进行操作", "success");

      // 保存录制状态到storage
      await chrome.storage.local.set({
        isRecording: true,
        recordedActions: [],
      });
    } catch (error) {
      console.error("开始录制失败:", error);
      updateStatus("录制启动失败: " + error.message, "error");
      updateRecordingUI(false, 0);
    } finally {
      recordBtnEl.disabled = false;
    }
  }

  /**
   * 停止录制
   */
  async function stopRecording() {
    try {
      updateStatus("正在停止录制...", "info");
      recordBtnEl.disabled = true;

      const tab = await checkCurrentTab();
      const response = await chrome.tabs.sendMessage(tab.id, { type: "STOP_RECORDING" });

      if (response?.success) {
        recordedActions = response.actions || [];
        updateRecordingUI(false, recordedActions.length);

        const message = recordedActions.length > 0 ? `录制完成，共记录 ${recordedActions.length} 个操作` : "录制完成，但没有记录到任何操作";
        const type = recordedActions.length > 0 ? "success" : "warning";
        updateStatus(message, type);

        // 保存录制状态到storage
        await chrome.storage.local.set({
          isRecording: false,
          recordedActions: recordedActions,
        });
      } else {
        throw new Error(response?.error || "停止录制失败");
      }
    } catch (error) {
      console.error("停止录制失败:", error);
      updateStatus("录制停止失败: " + error.message, "error");
      updateRecordingUI(false, 0);
      await chrome.storage.local.set({ isRecording: false });
    } finally {
      recordBtnEl.disabled = false;
    }
  }

  /**
   * 取消录制
   */
  async function cancelRecording() {
    try {
      updateStatus("正在取消录制...", "info");

      const tab = await checkCurrentTab();
      await chrome.tabs.sendMessage(tab.id, { type: "STOP_RECORDING" });

      // 清空录制数据
      recordedActions = [];
      updateRecordingUI(false, 0);
      updateStatus("录制已取消", "info");

      // 清除storage中的录制状态
      await chrome.storage.local.set({
        isRecording: false,
        recordedActions: [],
      });
    } catch (error) {
      console.error("取消录制失败:", error);
      updateStatus("取消录制失败", "error");
    }
  }

  /**
   * 导出录制文件
   */
  function exportRecording() {
    if (recordedActions.length === 0) {
      updateStatus("没有可导出的录制数据", "warning");
      return;
    }

    try {
      // 计算录制统计信息
      const startTime = recordedActions.length > 0 ? recordedActions[0].timestamp : 0;
      const endTime = recordedActions.length > 0 ? recordedActions[recordedActions.length - 1].timestamp : 0;
      const duration = endTime - startTime;
      
      // 计算操作间隔统计
      const intervals = [];
      for (let i = 1; i < recordedActions.length; i++) {
        intervals.push(recordedActions[i].timestamp - recordedActions[i - 1].timestamp);
      }
      
      const avgInterval = intervals.length > 0 ? intervals.reduce((a, b) => a + b, 0) / intervals.length : 0;
      const minInterval = intervals.length > 0 ? Math.min(...intervals) : 0;
      const maxInterval = intervals.length > 0 ? Math.max(...intervals) : 0;

      const exportData = {
        version: "1.0.0",
        timestamp: new Date().toISOString(),
        url: "",
        title: "浏览器工作流录制",
        actions: recordedActions,
        metadata: {
          userAgent: navigator.userAgent,
          totalActions: recordedActions.length,
          duration: duration,
          recordingStartTime: startTime,
          recordingEndTime: endTime,
          timingStatistics: {
            averageInterval: Math.round(avgInterval),
            minInterval: minInterval,
            maxInterval: maxInterval,
            hasValidTimings: recordedActions.every(action => action.timestamp && action.relativeTime !== undefined)
          },
          exportedAt: Date.now(),
          supportedPlaybackModes: ["fixed-interval", "original-timings"]
        },
      };

      // 获取当前页面信息
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        if (tabs[0]) {
          exportData.url = tabs[0].url;
          exportData.title = `${tabs[0].title} - 工作流录制`;
        }

        const dataStr = JSON.stringify(exportData, null, 2);
        const blob = new Blob([dataStr], { type: "application/json" });
        const url = URL.createObjectURL(blob);

        const a = document.createElement("a");
        a.href = url;
        a.download = `browser-workflow-${new Date().toISOString().split("T")[0]}.json`;
        a.click();

        URL.revokeObjectURL(url);
        updateStatus("录制文件已导出", "success");
      });
    } catch (error) {
      console.error("导出失败:", error);
      updateStatus("导出失败: " + error.message, "error");
    }
  }

  /**
   * 导入并开始回放
   */
  function importAndPlayback() {
    importFileEl.click();
  }

  /**
   * 处理文件导入并自动开始回放
   */
  function handleFileImport(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = async function (e) {
      try {
        const importData = JSON.parse(e.target.result);
        // 延迟500ms后关闭窗口
        setTimeout(() => {
          window.close();
        }, 500);

        // 验证文件格式
        if (!importData.actions || !Array.isArray(importData.actions)) {
          throw new Error("无效的录制文件格式");
        }

        if (importData.actions.length === 0) {
          throw new Error("录制文件中没有操作数据");
        }

        updateStatus(`已导入 ${importData.actions.length} 个操作，开始回放...`, "info");

        // 自动开始回放
        await startPlayback(importData.actions);
      } catch (error) {
        console.error("导入文件失败:", error);
        updateStatus("导入失败：" + error.message, "error");
      }
    };

    reader.readAsText(file);
    event.target.value = ""; // 清空文件选择
  }

  /**
   * 开始回放
   */
  async function startPlayback(actions) {
    if (!actions?.length) {
      updateStatus("没有可回放的录制数据", "warning");
      return;
    }

    try {
      const tab = await checkCurrentTab();
      await ensureContentScript(tab.id);

      // 禁用回放按钮
      playbackBtnEl.disabled = true;
      playbackBtnEl.innerHTML = "<span>⏳</span> 回放中...";

      // 向content script发送回放数据
      const response = await chrome.tabs.sendMessage(tab.id, {
        type: "START_PLAYBACK",
        data: { actions: actions },
      });

      if (!response?.success) {
        throw new Error(response?.error || "回放启动失败");
      }

      updateStatus(`回放已开始，共 ${actions.length} 个操作`, "success");

      // 监听回放完成
      const messageListener = function (request, sender, sendResponse) {
        if (request.type === "PLAYBACK_COMPLETE") {
          resetPlaybackUI();
          updateStatus("回放完成", "success");
          chrome.runtime.onMessage.removeListener(messageListener);
        } else if (request.type === "PLAYBACK_ERROR") {
          resetPlaybackUI();
          updateStatus("回放失败：" + request.error, "error");
          chrome.runtime.onMessage.removeListener(messageListener);
        }
      };

      chrome.runtime.onMessage.addListener(messageListener);

      // 5分钟超时
      setTimeout(() => {
        if (playbackBtnEl.disabled) {
          resetPlaybackUI();
          updateStatus("回放超时", "error");
          chrome.runtime.onMessage.removeListener(messageListener);
        }
      }, 300000);
    } catch (error) {
      console.error("回放失败:", error);
      updateStatus("回放失败: " + error.message, "error");
      resetPlaybackUI();
    }
  }

  /**
   * 重置回放UI状态
   */
  function resetPlaybackUI() {
    playbackBtnEl.disabled = false;
    playbackBtnEl.innerHTML = "<span>🎬</span> 导入并回放";
  }

  /**
   * 加载并显示回放配置
   */
  async function loadPlaybackConfig() {
    try {
      const config = await chrome.storage.sync.get(['useOriginalTimings', 'playbackSpeed']);
      
      const useOriginalTimings = config.useOriginalTimings || false;
      const speed = config.playbackSpeed || 500;
      
      // 更新回放模式显示
      if (useOriginalTimings) {
        timingModeEl.textContent = "原始时间间隔";
        timingModeEl.style.color = "#28a745";
        playbackSpeedEl.textContent = "动态调整";
        playbackSpeedEl.style.color = "#6c757d";
      } else {
        timingModeEl.textContent = "固定间隔";
        timingModeEl.style.color = "#007bff";
        playbackSpeedEl.textContent = speed + "ms";
        playbackSpeedEl.style.color = "#007bff";
      }
    } catch (error) {
      console.error("加载回放配置失败:", error);
      timingModeEl.textContent = "加载失败";
      playbackSpeedEl.textContent = "加载失败";
    }
  }

  /**
   * 初始化状态
   */
  async function initializeState() {
    try {
      updateStatus("正在加载状态...", "info");

      // 从storage加载状态
      const result = await chrome.storage.local.get(["isRecording", "recordedActions"]);

      if (result.isRecording) {
        // 检查content script是否真的在录制
        try {
          const tab = await checkCurrentTab();
          await ensureContentScript(tab.id);

          const response = await chrome.tabs.sendMessage(tab.id, { type: "GET_RECORDING_STATUS" });

          if (response?.isRecording) {
            isRecording = true;
            recordedActions = result.recordedActions || [];
            updateRecordingUI(true, recordedActions.length);
            updateStatus("检测到正在进行的录制", "info");
          } else {
            // content script不在录制，清除storage状态
            await chrome.storage.local.set({ isRecording: false });
            updateRecordingUI(false, 0);
            updateStatus("就绪", "info");
          }
        } catch (error) {
          // 如果无法连接到content script，清除录制状态
          await chrome.storage.local.set({ isRecording: false });
          updateRecordingUI(false, 0);
          updateStatus("就绪", "info");
        }
      } else {
        recordedActions = result.recordedActions || [];
        updateRecordingUI(false, recordedActions.length);
        updateStatus("就绪", "info");
      }
    } catch (error) {
      console.error("初始化状态失败:", error);
      updateStatus("初始化失败", "error");
    }
  }

  // 事件监听器
  recordBtnEl.addEventListener("click", function () {
    if (isRecording) {
      stopRecording();
    } else {
      startRecording();
    }
  });

  playbackBtnEl.addEventListener("click", importAndPlayback);
  importFileEl.addEventListener("change", handleFileImport);
  exportBtnEl.addEventListener("click", exportRecording);
  cancelBtnEl.addEventListener("click", cancelRecording);
  optionsBtnEl.addEventListener("click", function () {
    chrome.runtime.openOptionsPage();
  });

  // 监听来自content script的消息
  chrome.runtime.onMessage.addListener(function (request) {
    if (request.type === "ACTION_RECORDED") {
      // 更新录制状态显示
      const currentCount = recordedActions.length + 1;
      const statusText = recordStatusEl.querySelector(".status-text");
      if (statusText && isRecording) {
        statusText.textContent = `正在录制... (${currentCount} 个操作)`;
      }
    }
  });

  // 监听设置变化
  chrome.storage.onChanged.addListener(function(changes, areaName) {
    if (areaName === 'sync' && (changes.useOriginalTimings || changes.playbackSpeed)) {
      loadPlaybackConfig();
    }
  });

  // 初始化
  initializeState();
  loadPlaybackConfig();
});
